package com.example.nfcschool;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.example.nfcschool.TListActivity.loadJsp;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class JoinActivity extends Activity implements OnClickListener{

	TextView end_text;
	SmemberVO m ;
	String telno="";
	String teach="";
	SharedPreferences sp;
	Editor edit;
	boolean cheeting = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join);
	
		ActionBar actionBar = getActionBar();
        actionBar.hide();
		
		EditText et = (EditText)findViewById(R.id.irum_edit);
		et.requestFocus();
		
		end_text = (TextView)findViewById(R.id.go_textbtn);
		end_text.setOnClickListener(this);
		
		sp = getSharedPreferences("teachdata", Activity.MODE_PRIVATE);
		edit = sp.edit();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch(id){
		case R.id.go_textbtn:
			SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
			m = new SmemberVO();
			
			// 전화번호,IMEI 가져오기. 
			TelephonyManager tele = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
	    	telno = tele.getLine1Number();
	    	if(telno.contains("+82")) {
	    		telno = "0"+telno.substring(3);
	    	}
			
	    	String irum_et = ((EditText)findViewById(R.id.irum_edit)).getText().toString();
			String grade_et = ((EditText)findViewById(R.id.grade_edit)).getText().toString();
			String pw_et = ((EditText)findViewById(R.id.pw_edit)).getText().toString();
			String birth_et = ((EditText)findViewById(R.id.birth_edit)).getText().toString();
			String add_et = ((EditText)findViewById(R.id.adds_edit)).getText().toString();
			CheckBox teach_ch  = (CheckBox)findViewById(R.id.teach_check);
			String sno_et = ((EditText)findViewById(R.id.sno_edit)).getText().toString();
			String pic_et = ((EditText)findViewById(R.id.picture_edit)).getText().toString();
			
			
			
			teach = "false";
			if(teach_ch.isChecked()) teach = "true";
			
			// 공백값 잡기
			if(irum_et.equals("")){
				findViewById(R.id.irum_edit).requestFocus();
				Toast.makeText(this, "빈 항목이 있습니다.", Toast.LENGTH_SHORT).show();
				return;
			}else if(grade_et.equals("")){
				findViewById(R.id.grade_edit).requestFocus();
				Toast.makeText(this, "빈 항목이 있습니다.", Toast.LENGTH_SHORT).show();
				return;
			}else if(pw_et.equals("")){
				findViewById(R.id.pw_edit).requestFocus();
				Toast.makeText(this, "빈 항목이 있습니다.", Toast.LENGTH_SHORT).show();
				return;
			}else if(birth_et.equals("")){
				findViewById(R.id.birth_edit).requestFocus();
				Toast.makeText(this, "빈 항목이 있습니다.", Toast.LENGTH_SHORT).show();
				return;
			}else if(add_et.equals("")){
				findViewById(R.id.adds_edit).requestFocus();
				Toast.makeText(this, "빈 항목이 있습니다.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			// 기타 제약조건
			String[] grade = grade_et.split("-");
			if(grade.length != 2){
				findViewById(R.id.grade_edit).requestFocus();
				Toast.makeText(this, "학반이 올바르지 않습니다.", Toast.LENGTH_SHORT).show();
				return;
			}else if(pw_et.length() != 4){
				findViewById(R.id.pw_edit).requestFocus();
				Toast.makeText(this, "암호는 네 자리 숫자입니다.", Toast.LENGTH_SHORT).show();
				return;
			}else if((birth_et.length() != 8)){
				findViewById(R.id.birth_edit).requestFocus();
				Toast.makeText(this, "생년월일을 확인해주세요.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if(birth_et.length() == 8){
				int year = Integer.parseInt(birth_et.substring(0, 4));
				int month = Integer.parseInt(birth_et.substring(4, 6));
				int day = Integer.parseInt(birth_et.substring(6, 8));
				if(year<1950 || year>2014 || month>12 || day>31){
					findViewById(R.id.birth_edit).requestFocus();
					Toast.makeText(this, "생년월일을 확인해주세요.", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			
			m.setTel(telno);
			m.setIrum(irum_et);
			m.setGrade(grade_et);
			m.setPw(Integer.parseInt(pw_et));
			m.setBirth(birth_et);
			m.setAdds(add_et);
			m.setTeach(teach);
//			Log.d("Join Sno_et.Length()",""+sno_et.length());
//			if(sno_et.length()==1) sno_et = "0"+sno_et;
			m.setSno(sno_et); // 번호칸 생성되면 변경하기.
			m.setPicture(pic_et);
			
			
			
			Intent intent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			startActivity(intent);
			cheeting = false;
			Toast.makeText(this, "다시 로그인 해주세요.", Toast.LENGTH_SHORT).show();
			edit.putString("grade", grade_et);
			edit.commit();
			new JoinJsp().execute();
			
		}
	}
	
	// Font_Join
	protected void onStart() {
		Typeface typeFace = Typeface.createFromAsset(getAssets(), "white.ttf");
		
		TextView tv1 = (TextView)findViewById(R.id.textView1);
		TextView tv2 = (TextView)findViewById(R.id.textView2);
        TextView tv3 = (TextView)findViewById(R.id.textView3);
        TextView tv4 = (TextView)findViewById(R.id.textView4);
        TextView tv5 = (TextView)findViewById(R.id.textView5);
        TextView tv6 = (TextView)findViewById(R.id.textView6);
        TextView tv7 = (TextView)findViewById(R.id.go_textbtn);
        TextView tv8 = (TextView)findViewById(R.id.textView07);
        TextView tv9 = (TextView)findViewById(R.id.textView08);
		
//        CheckBox cb = (CheckBox)findViewById(R.id.teach_check);
		
		tv1.setTypeface(typeFace);
		tv2.setTypeface(typeFace);
		tv3.setTypeface(typeFace);
		tv4.setTypeface(typeFace);
		tv5.setTypeface(typeFace);
		tv6.setTypeface(typeFace);
		tv7.setTypeface(typeFace);
		tv8.setTypeface(typeFace);
		tv9.setTypeface(typeFace);
		
//		cb.setTypeface(typeFace);
		
		super.onStart();
	}
	
	
	// ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡWebDB
	public class JoinJsp extends AsyncTask<Void, String, Void> {
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.10.67:8888/AndroidCheck/JoinDB.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				String snoo = m.getSno();
				if(snoo.length()==1)snoo = "0"+snoo;
				
				params.add(new BasicNameValuePair("tel", m.getTel()));
				params.add(new BasicNameValuePair("irum", m.getIrum()));
				params.add(new BasicNameValuePair("grade", m.getGrade()));
				params.add(new BasicNameValuePair("pw", m.getPw()+""));
				params.add(new BasicNameValuePair("birth", m.getBirth()));
				params.add(new BasicNameValuePair("adds", m.getAdds()));
				params.add(new BasicNameValuePair("teach", m.getTeach()));
				params.add(new BasicNameValuePair("sno", snoo));
				params.add(new BasicNameValuePair("picture", m.getPicture()));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();

				if (resEntity != null) {
					Log.i("RESPONSE", EntityUtils.toString(resEntity));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.e("joinend?", "end?");
			super.onPostExecute(result);
		}
	}
	
	@Override
	protected void onStop() {
		if (cheeting) {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
			try {
				Toast.makeText(getApplicationContext(), "Into try/catch",
						Toast.LENGTH_LONG).show();
				Class localClass = connectivityManager.getClass();
				Class[] arrayOfClass = new Class[1];
				arrayOfClass[0] = Boolean.TYPE;
				Method localMethod = localClass.getMethod(
						"setMobileDataEnabled", arrayOfClass);
				ConnectivityManager localConnectivityManager = connectivityManager;
				Object[] arrayOfObject = new Object[1];
				arrayOfObject[0] = Boolean.valueOf(false);
				localMethod.invoke(localConnectivityManager, arrayOfObject);
				WifiManager wifiManager = (WifiManager) getApplicationContext()
						.getSystemService(Context.WIFI_SERVICE);
				wifiManager.setWifiEnabled(false);

			} catch (Exception e) {
				e.printStackTrace();
			}
			FileOutputStream fos = null;
			Toast.makeText(getApplicationContext(), "데이터차단!!", 2000).show();
			fos = null;
			try {
				// 첫 매개변수는 파일명, 두번째 매개변수는 모드
				fos = openFileOutput("networkcheck", Activity.MODE_PRIVATE);

				String check1 = "true";
				fos.write(check1.getBytes());
				fos.close();
				Toast.makeText(getApplicationContext(), "파일이 저장되었습니다.",
						Toast.LENGTH_SHORT).show();
			} catch (Exception ex) {
				Log.e("파일 save 에러", ex.toString());
			}
		}
		super.onPause();
	}
	
	
	
	
	
}
